package da.metricscraft.listeners;


import java.util.HashMap;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityTargetEvent.TargetReason;

import da.metricscraft.MetricsCraft;
import da.metricscraft.information.PlayerInformation.PlayerDataType;

public class MetricsEntityListener implements Listener{
	private static MetricsCraft plugin;
	private HashMap<Integer, Player> lastDamageDealtFrom;
	public MetricsEntityListener(MetricsCraft plugin){
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
		MetricsEntityListener.plugin = plugin;
		lastDamageDealtFrom = new HashMap<Integer, Player>();
	}
	@EventHandler
	public void onEntityDeath(EntityDeathEvent event) {
		
		if (!(event.getEntity() instanceof Player)){
			if (lastDamageDealtFrom.containsKey(event.getEntity().getEntityId())){
				if (lastDamageDealtFrom.get(event.getEntity().getEntityId()) != null)
					plugin.addPlayerData(lastDamageDealtFrom.get(event.getEntity().getEntityId()), PlayerDataType.KILLS, 1);				
			}
		}else{
			plugin.addPlayerData((Player)event.getEntity(), PlayerDataType.DEATHS, 1);
		}
	}
	@EventHandler
	public void onEntityRegainHealth(org.bukkit.event.entity.EntityRegainHealthEvent event) {
		if (event.getEntity() instanceof Player){
			Player player = (Player)event.getEntity();
			if (plugin.enabled(player)){
				plugin.addPlayerData(player, PlayerDataType.HEALTH_REGAINED, event.getAmount());
			}
		}
	}
	@EventHandler
	public void onEntityDamage(EntityDamageEvent event) {
		if (event.getEntity() instanceof Player){
			Player player = (Player)event.getEntity();
			if (plugin.enabled(player)){
				if (PlayerDataType.valueOf("DAMAGE_TAKEN_" + event.getCause().name()) != null)
					plugin.addPlayerData(player, PlayerDataType.valueOf("DAMAGE_TAKEN_" + event.getCause().name()), event.getDamage());
			}
		}else{
			if (event.getCause() != DamageCause.ENTITY_ATTACK){
				lastDamageDealtFrom.put(event.getEntity().getEntityId(), null);
			}
		}
	}
	
	@EventHandler(priority = EventPriority.HIGH)
	public void onEntityTarget(EntityTargetEvent event){
		if (event.getTarget() instanceof Player){
			Player player = (Player)event.getTarget();
			if (plugin.enabled(player) && event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY){
				lastDamageDealtFrom.put(event.getEntity().getEntityId(), player);
			}
		}
		
	}
}
